#pragma once
#include "Protocol.hpp"

enum
{
    Div_Zero = 1,
    Mod_Zero,
    Other_oper
};

class calc
{
public:
    calc()
    {
    }

    ~calc()
    {
    }

public:
    // 计算
    Response CalculatorHelper(const Request &req)
    {
        Response resp(0, 0);
        switch (req.op)
        {
        case '+':
            resp.result = req.x + req.y;
            break;
        case '-':
            resp.result = req.x - req.y;
            break;
        case '*':
            resp.result = req.x * req.y;
            break;
        case '/':
            if (req.y == 0)
            {
                resp.errcode = Div_Zero;
            }
            resp.result = req.x / req.y;
            break;
        case '%':
            if (req.y == 0)
            {
                resp.errcode = Mod_Zero;
            }
            resp.result = req.x % req.y;
            break;
        default:
            resp.errcode = Other_oper;
            break;
        }

        return resp;
    }

    // 传入客户端发送请求，返回响应处理报文
    std::string Calculator(std::string &package)
    {
        std::string content;
        bool n = Decode(package, &content);
        if (!n)
            return "";

        Request req;
        n = req.Deserialize(content);
        if (!n)
            return "";

        Response resp = CalculatorHelper(req);

        content = "";
        resp.Serialize(&content);

        content = Encode(content);

        return content;
    }
};